package com.baizhi.comtroller;

import com.baizhi.entity.T_user;
import com.baizhi.entity.T_files;
import com.baizhi.service.UserFIleService;


import com.baizhi.service.ex.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;


import java.io.FileNotFoundException;
import java.io.IOException;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("file")
public class FileController {

    // 文件下载路径
    @Value("${upload.path}")
    String path;


    @Autowired
    UserFIleService userFIleService;

    /**
     * 查询所有文件
     */
    @RequestMapping("showAll")
    String findAll(HttpSession session, Model model){

        // 用户信息
        T_user user = (T_user) session.getAttribute("user");

        // 登陆用户的所有文件
        List<T_files> files = userFIleService.selectByUserID(user.getId());

        model.addAttribute("files", files);


        return "showAll";
    }

    /**
     * 上传文件到数据库
     */
    @PostMapping("upload")
    String upload(MultipartFile aaa, HttpSession session) throws IOException {

        // 获取用户对象
        T_user t_user_obj = (T_user) session.getAttribute("user");


        // 旧文件名
        String OldFileName = aaa.getOriginalFilename();

        // 如果是空文件则报错
        if(OldFileName == null || OldFileName.equals("")){
            return "redirect:/file/showAll";
        }

        // 后缀
        String Ext = OldFileName.substring(OldFileName.lastIndexOf("."));

        // 生成随机的文件名
        String NewFileName = UUID.randomUUID().toString() + Ext;

        // 获取文件大小
        Long size = aaa.getSize();
        
        // 获取文件类型
        String type = aaa.getContentType();






        // 动态获取文件保存路径
        String savePath = path;



        // 根据日期创建文件夹
        String dateFIle = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

        // 文件最终保存目录
        String dataDir = savePath + "/" + dateFIle;


        // 判断设定的文件保存路径是否存在，不存在则创建
        File dir = new File(dataDir);
        if(!dir.exists()){
            dir.mkdirs();
        }


        aaa.transferTo(new File(dir + "/" + NewFileName));
        System.err.println("文件保存路径：" + dir + "/" + NewFileName);







        T_files obj = new T_files();
        obj.setOldFileName(OldFileName);
        obj.setNewFileName(NewFileName);
        obj.setExt(Ext);
        obj.setPath(dataDir);
        obj.setSize(String.valueOf(size));
        obj.setType(type);
        obj.setDownCounts(0);
        obj.setUploadTime(new Date());
        obj.setUserId(t_user_obj.getId());

        // 判断是否是图片
        String isImg = obj.getType().startsWith("image")?"是":"否";
        obj.setIsImg(isImg);

        userFIleService.save(obj);


        return "redirect:/file/showAll";
    }

    /**
     * 文件下载
     */
    @GetMapping("download")
    void download(Integer id, HttpServletResponse response, String openStyle) throws IOException {

        // 判断是下载还是在线打开
        openStyle = openStyle==null?"attachment":openStyle;


        T_files byId = userFIleService.getById(id);     // 文件保存信息

        // 更新下载次数
        if (openStyle.equals("attachment")){
            userFIleService.updateDownCounts(byId);
        }


        // 文件下载
        userFIleService.fileDownLoad(byId, response, openStyle);

    }


    /**
     * 删除
     */
    @GetMapping("delete")
    String delete(Integer id) throws FileNotFoundException {

        T_files byId = userFIleService.getById(id);

        // 删除保存的文件
        userFIleService.delete(byId);


        // 删除数据库数据
        userFIleService.removeById(id);

        return "redirect:/file/showAll";
    }

}
